package cn.kailangtu.dataspot;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.provider.Settings;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.kailangtu.commontools.CommonUtils;
import cn.kailangtu.commontools.DataUtils;
import cn.kailangtu.dataspot.data.ExceptionData;
import cn.kailangtu.dataspot.db.ExceptionLogEntity;
import cn.kailangtu.modbus.ModbusSlave;
import cn.kailangtu.modbus.SpecialData;

/**
 * Created by fujf on 2021/12/2
 * Description:
 */
public class AppBasicMethod {
    private static AppBasicMethod instance;
    /*
     * 单例模式创建
     * */
    public static AppBasicMethod getInstance() {
        if (instance == null) {
            instance = new AppBasicMethod();
        }
        return instance;
    }

    private static Context mContext;
    private static Application mApplication;
    public void setContext(Context con){
        mContext = con;
        cacheThreadPool = Executors.newCachedThreadPool();
    }

    public void setApplication(Application app)
    {
        mApplication = app;
    }

    public Context getContext(){
        return mContext;
    }

    public Application getApplication(){
        return mApplication;
    }

    // APP线程管理类
    private ExecutorService cacheThreadPool;
    public ExecutorService getExecutorService(){
        return cacheThreadPool;
    }

    public void hideKeyboard(Activity mActivity){
        View view = mActivity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) mActivity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void goAndSetView() {
        Intent intentYIDONG = new Intent(Settings.ACTION_SETTINGS);
        intentYIDONG.putExtra("extra_prefs_show_button_bar", true);
        intentYIDONG.putExtra("extra_prefs_set_back_text", "返回");
        intentYIDONG.putExtra("extra_prefs_set_next_text", "");
        mContext.startActivity(intentYIDONG); //直接进入手机中的移动网络设置界面
    }

    public void goDesktop() {
        Intent home = new Intent(Intent.ACTION_MAIN);
        // 为Intent设置Action、Category属性
        home.setAction(Intent.ACTION_MAIN);// "android.intent.action.MAIN"
        home.addCategory(Intent.CATEGORY_HOME); //"android.intent.category.HOME"
        mContext.startActivity(home);
    }

    /**
     * 生成UUID
     */
    public String getUUID() {
        return UUID.randomUUID().toString();
    }



    /**
     * 两次点击按钮之间的点击间隔不能少于500毫秒
     */
    private final int MIN_CLICK_DELAY_TIME = 500;
    private long lastClickTime;
    public boolean fz防止重复点击事件() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
            lastClickTime = curClickTime;
        }
        return flag;
    }




    /**
     * 生成几位随机数或字母的组合
     */
    public String getRandomNum(int no) {
        int maxNum = 36;
        int i;
        int count = 0;
        char[] str = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer sb = new StringBuffer("");
        Random r = new Random();
        while (count < no) {
            i = Math.abs(r.nextInt(maxNum));
            if (i >= 0 && i < str.length) {
                sb.append(str[i]);
                count++;
            }
        }
        return sb.toString();
    }

    /*
     * 将res/raw下的文件保存至SD卡
     * */
    public void saveToSDCard(String filePath, int id_raw) throws Throwable {
        InputStream inputStream = getContext().getResources().openRawResource(id_raw);
        File file = new File(filePath);
        // 1.建立通道对象
        FileOutputStream fos = new FileOutputStream(file);
        // 2.定义存储空间
        byte[] buffer = new byte[inputStream.available()];
        // 3.开始读文件
        int lenght = 0;
        while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
            // 将Buffer中的数据写到outputStream对象中
            fos.write(buffer, 0, lenght);
        }
        fos.flush();// 刷新缓冲区
        // 4.关闭流
        fos.close();
        inputStream.close();
    }

    public void startApp(){
        String packageName = PackageUtils.getInstance().get获取App包名();
        Intent LaunchIntent = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
        mContext.startActivity(LaunchIntent);
    }


    public void startBzAppIsTopThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (isCanBzAppIsTop) {
                       //L.smEE("保证APP一直显示线程，开始：" + Thread.currentThread().getName());
                        while (isCanBzAppIsTop) {
                            int time = 5 * 1000;
                            noBzAppIsTopTimeCur += time;
                            SystemClock.sleep(time);
                            if (isCanBzAppIsTop) {
                                if (noBzAppIsTopTimeCur > noBzAppIsTopTimeAll) {
                                    setTopApp();
                                    isSetTopAppThtead();
                                    restartBzAppIsTopTimer();
                                }
                            }
                        }
                        //L.smEE("保证APP一直显示线程，结束：" + Thread.currentThread().getName());
                    }
                }
            }
        }).start();
    }
    private int noBzAppIsTopTimeCur = 0;
    private int noBzAppIsTopTimeAll = 30 * 1000;
    private boolean isCanBzAppIsTop = true;
    public void restartBzAppIsTopTimer() {
        noBzAppIsTopTimeCur = 0;
        noBzAppIsTopTimeAll = 30 * 1000;
        isCanBzAppIsTop = true;
    }

    private void isSetTopAppThtead(){
        getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(3 * 1000);
                isSetTopApp();
            }
        });
    }



    private int noSetTopApp = 0;
    private void isSetTopApp(){
        boolean topActivity = isRunningForeground();
        if (topActivity) {
            noSetTopApp = 0;
        } else {
            noSetTopApp++;
        }
        if (noSetTopApp >= 3) {
            //L.smEE("APP长时间未处于前台重启，已触发！");
            // 3秒一次，连续检测到5次设备未处于购买状态再重启(多次检测是否处于购买状态)
            int disOpeningCount = 0;
            while (true) {
                try {
                    boolean isHandler = false;
                   // L.smEE("APP长时间未处于前台重启，门锁当前状态(是否有人正在购买)：" + isHandler);
                    if (isHandler) {
                        disOpeningCount = 0;
                    }else {
                        disOpeningCount++;
                    }
                    if (disOpeningCount > 5) {
                      //  L.smEE("APP长时间未处于前台重启，成功");
                        //AppBasicMethod.getInstance().sendEbApp(6, "APP长时间未处于前台重启！");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                SystemClock.sleep(1000);
                            //    AppBasicMethod.getInstance().sendEbApp(2);
                            }
                        }).start();
                        break;
                    }
                } catch (Exception e) {
                   // L.smEE("APP长时间未处于前台重启，异常：" + e.toString());
                }
                SystemClock.sleep(3 * 1000);
            }
        }
    }



    /**
     * 判断当前应用是否在前台
     * 系统签名的应用，可以获取其他应用进程，当前是否在前台 ，非系统签名应用只能获取自己的
     */
    private boolean isRunningForeground() {
        try {
            ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
            if (runningAppProcesses == null) {
                return false;
            }
            String packageName = PackageUtils.getInstance().get获取App包名();
            for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : runningAppProcesses) {
                String strProcessName = runningAppProcessInfo.processName;
                int importance = runningAppProcessInfo.importance;
                if (packageName.equalsIgnoreCase(strProcessName) &&
                        importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return true;
                }
            }
            return  false;
        } catch (Exception e) {
           // Logger.e(e, "判断本应用是否在最前端，异常！");
            return false;
        }
    }

    /**
     * 将本应用置顶到最前端
     * 当本应用位于后台时，则将它切换到最前端
     */
    private void setTopApp() {
//        L.smEE("将本应用置顶到最前端，开始");
        try {
            String packageName = PackageUtils.getInstance().get获取App包名();
            /**获取ActivityManager*/
            ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
            /**获得当前运行的task(任务)*/
            List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(100);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                /**找到本应用的 task，并将它切换到前台*/
                if (taskInfo.topActivity.getPackageName().equals(packageName) || taskInfo.baseActivity.getPackageName().equals(packageName)) {
                    activityManager.moveTaskToFront(taskInfo.id, 0);
//                    L.smEE("将本应用置顶到最前端，执行");
                    break;
                }
            }
        } catch (Exception e) {
//            Logger.e(e, "将本应用置顶到最前端，异常！");
        }
    }

    public  void processExceptionLog()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<ExceptionLogEntity> lsFind =   LitePal.order("logNumber DESC").limit(10).find(ExceptionLogEntity.class);
                List<ExceptionData> ls = new ArrayList<>();
                int index = 0;
                byte[] data = new byte[140];
                for(ExceptionLogEntity item : lsFind){
                    byte[] dateTime6 =  DataUtils.timeToByte6( new Date( item.getCreateTime()));
                    byte[] errCode = CommonUtils.int2ByteArray(item.getDataSource());
                    byte[] data1 = CommonUtils.int2ByteArray(item.getDataErr1());
                    byte[] data2 = CommonUtils.int2ByteArray(item.getDataErr2());
                    byte[] data3 = CommonUtils.int2ByteArray(item.getDataErr3());

                    byte[] all = new byte[14];
                    System.arraycopy(dateTime6,0,all,0,6);
                    System.arraycopy(errCode,0,all,6,2);
                    System.arraycopy(data1,0,all,8,2);
                    System.arraycopy(data2,0,all,10,2);
                    System.arraycopy(data3,0,all,12,2);

                    System.arraycopy(all,0,data,14*index,14);

                    index++;
                }

                SpecialData.setExceptionLog(data);

            }
        }).start();

    }


}
